package com.jinyi.wwdeng.ui.permission

import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.permissions.XXPermissions
import com.jinyi.base.utils.log.HHLog
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActPermissionBinding
import com.jinyi.wwdeng.pro.ProAct
import com.jinyi.wwdeng.ui.login.LoginAct
import com.jinyi.wwdeng.ui.permission.adapter.PermissionAdapter
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.dialog.TipsDialog
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONArray
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/16 14:26
 * @Annotation：权限列表
 */
class PermissionAct: ProAct() {
    private lateinit var binding: ActPermissionBinding

    //权限列表
    private val mPermissionList = arrayListOf<JSONObject>()
    //当前显示的权限
    var mPermissionIndex = 0

    //权限描述列表
    private var mItemAdapter: PermissionAdapter? = null

    override fun getRootView(): View {
        binding = ActPermissionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTextTitle(getString(R.string.get_permission))
        setTextTitleGravity(Gravity.CENTER)
        setRightBtnVisibility(View.GONE)

        initRecyclerView()
    }

    override fun initListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"Permission Page")
        }
        //上一个
        binding.lastLayout.setOnClickListener {
            if (mPermissionIndex == 0){
                return@setOnClickListener
            }
            mPermissionIndex--
            showCurrentPermission()
            val item = mPermissionList[mPermissionIndex]
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_LAST,item.optString("permission"))
        }
        //下一个
        binding.nextLayout.setOnClickListener {
            if (mPermissionIndex == mPermissionList.size - 1){
                return@setOnClickListener
            }
            mPermissionIndex++
            showCurrentPermission()
            val item = mPermissionList[mPermissionIndex]
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_NEXT,item.optString("permission"))
        }
        //拒绝权限
        binding.btnDeny.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            item.put("isDeny",true)
            if (!item.optBoolean("isMust")){//非必须权限，需要设置为已点击状态
                item.put("isClick",true)
            }
            showPermissionBanned()
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_DENY,item.optString("permission"))
            mPermissionIndex = getPermissionIndex()
            showCurrentPermission()
        }
        //同意权限
        binding.btnAgree.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            val confirmDialog = TipsDialog(this,item.optString("permission"),object : TipsDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    when(view!!.id){
                        R.id.btnRight -> {
                            hasRequestPermissions(item)
                            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
                        }
                        R.id.btnLeft -> {
                            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
                        }
                    }
                }
            })
            confirmDialog.setCancelable(true)
            confirmDialog.setCanceledOnTouchOutside(false)
            confirmDialog.show()
            confirmDialog.setTipsTitle(resources.getString(R.string.kind_tips))
            confirmDialog.setTips(resources.getString(R.string.permission_confirm_tips))
            confirmDialog.setButtonDoubleText(resources.getString(R.string.cancel),resources.getString(R.string.ok))
            confirmDialog.setButtonDoubleBackgroundResource(R.drawable.base_circle_frame_e5e6e6,R.drawable.base_circle_fill_9fe76f)

            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_AGREE,item.optString("permission"))
        }
        //已授权
        binding.btnAuthorized.setOnClickListener{
            val permission = mPermissionList[mPermissionIndex]
//            XXPermissions.startPermissionActivity(this,permission)
        }
        //被禁止
        binding.btnBanned.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            XXPermissions.startPermissionActivity(this,item.optString("permission"))
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_BANNED,item.optString("permission"))
        }
    }

    override fun initData() {
        mPermissionList.clear()
        val pDataArray = getPermissionArray()
        //手动添加一条
        pDataArray.put(getString(R.string.permission_app_list_data_collection))
        for (i in 0..<pDataArray.length()){
            val permission = pDataArray.optString(i)
            mPermissionList.add(PermissionConfig.getPermissionItem(permission))
        }

//        mPermissionIndex = getPermissionIndex()
        //是否全部授权
        if (isAgreeAll()){
            onIntent(LoginAct::class.java)
            finish()
            return
        }
        mPermissionIndex = getPermissionIndex()
        showCurrentPermission()
    }

    override fun onResume() {
        super.onResume()
        isHasPermissions()
    }

    /* 初始化列表 */
    private fun initRecyclerView(){
        binding.recyclerView.visibility = View.GONE
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(getContext())
        binding.recyclerView.layoutManager = layoutManager
        this.mItemAdapter = PermissionAdapter(binding.recyclerView)
        this.mItemAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mItemAdapter!!.getItem(position)
            when(childView.id){
                R.id.itemLayout -> {

                }
            }
        }
        binding.recyclerView.adapter = this.mItemAdapter
    }

    /**
     * 获取权限列表
     */
    private fun getPermissionArray(): JSONArray{
        val bundle = intent.extras
        return JSONArray(bundle!!.getString("Permissings"))
    }

    /**
     * 显示权限信息
     */
    private fun showCurrentPermission(){
        if (mPermissionIndex == -1){
            return
        }
        val item = mPermissionList[mPermissionIndex]

        val list = arrayListOf<JSONObject>()
        val obj = JSONObject()
        obj.put("title","Why we request your device sms data")
        obj.put("des","{APP name} will read the SMS information in your device, collect and analyze your financial SMS, and realize the assessment of your financial and debt status, so as to decide whether to approve your loan application.\n" +
                " your financial and debt status, so as to decide whether to approve your loan application.\n" +
                item.optString("permission")
        )
        list.add(obj)

        val obj2 = JSONObject()
        obj2.put("title","what you can do")
        obj2.put("des","You can choose to refuse the authorization, which will not affect your continued application for loans on the APP.You can choose to refuse the authorization, which will not affect your continued application for loans on the APP.You can choose to refuse the auhich will not affect your continued application for loans on the APP.\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorization\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorizationot affectto refuse the authorization\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorizationot affectto refuse the authorization\n" +
                item.optString("permission"))
        list.add(obj2)
        this.mItemAdapter!!.data  = list

        binding.ivPermissionIcon.setImageResource(item.optInt("icon"))
        binding.tvPermissionTitle.text = item.optString("title")
        binding.tvPermissionDes.text = item.optString("msg")
        binding.tvShowPermissionTitle.text = item.optString("title")
        isHasPermissions()
    }

    /**
     * 是否申请了允许了当前权限
     */
    private fun isHasPermissions(){
        if (isAgreeAll()){
            onIntent(LoginAct::class.java)
            finish()
            return
        }

        val item = mPermissionList[mPermissionIndex]
        //必须要申请的权限  APP LIST 只做展示
        if (item.optBoolean("isMust")){
            //是否已获得权限
            val isGranted = PermissionUtils.isAuthorized(this,item.optString("permission"))
            HHLog.e("${item.optString("permission")}>>>>>>>>是否已授权："+isGranted)
            //已获得权限
            if (isGranted){
                showPermissionAuthorized()
                return
            }
            //权限状态：0获取权限成功  1申请权限拒绝, 但是下次申请权限还会弹窗  2申请权限拒绝，并且是永久，不会再弹窗  3默认未请求授权状态
            val authorizeStaus = PermissionUtils.getAuthorizeStaus(this,item.optString("permission"))
            HHLog.e("${item.optString("permission")}>>>>>>>>状态：$authorizeStaus")
            //2申请权限拒绝，并且是永久，不会再弹窗 || 本次已拒绝
            if (authorizeStaus == 2 || item.optBoolean("isDeny",false)){
                showPermissionBanned()
                return
            }
            showPermissionNotObtained()
        } else {//非必须要申请的权限，根据isDeny 或 isAgree 显示状态
            if (item.optBoolean("isDeny")){
                showPermissionBanned()
                return
            }
            if (item.optBoolean("isAgree")){
                showPermissionAuthorized()
                return
            }
            showPermissionNotObtained()
        }
    }

    /**
     * 申请权限
     */
    fun hasRequestPermissions(item: JSONObject){
        //非必须申请的权限
        if (!item.optBoolean("isMust")){
            item.put("isAgree",true)
            item.put("isClick",true)
            showPermissionAuthorized()
            //验证是否全部已同意
            if (isAgreeAll()){
                onIntent(LoginAct::class.java)
                finish()
            } else {
                //最后一个
                if (mPermissionIndex == mPermissionList.size - 1){
                    mPermissionIndex = getPermissionIndex()
                } else {
                    mPermissionIndex++
                }
                showCurrentPermission()
            }
            return
        }
        val permission = item.optString("permission")
        PermissionUtils.requestPermission(this,permission,object : PermissionListener{
            override fun requestResult(isFlog: Boolean) {
                HHLog.e("requestResult>>>>>>>>>>>>>>$isFlog")
                if (isFlog){
                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permission)
                    showPermissionAuthorized()
                    //验证是否全部已同意
                    if (isAgreeAll()){
                        onIntent(LoginAct::class.java)
                        finish()
                        return
                    }
                } else {
                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,permission)
                    showPermissionBanned()
                }

                //最后一个
                if (mPermissionIndex == mPermissionList.size - 1){
                    mPermissionIndex = getPermissionIndex()
                } else {
                    mPermissionIndex++
                }
                showCurrentPermission()
            }
        })
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this,requestCode, permissions,grantResults)
    }

    /**
     * 未申请
     */
    private fun showPermissionNotObtained(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限未申请")
        binding.defaultLayout.visibility = View.VISIBLE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已允许
     */
    private fun showPermissionAuthorized(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限已允许")
        binding.defaultLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.VISIBLE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    private fun showPermissionBanned(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限已拒绝")
        binding.defaultLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.VISIBLE
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getPermissionIndex(): Int{
        var index = mPermissionIndex
        if (mPermissionList.size > 0){
            for (i in 0..<mPermissionList.size){
                val item = mPermissionList[i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(this,item.optString("permission")) && !item.optBoolean("isDeny",false)){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 是否全部已授权
     */
    private fun isAgreeAll(): Boolean{
        var isAll = true
        if (mPermissionList.size > 0){
            for (i in 0..<mPermissionList.size){
                val item = mPermissionList[i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(this,item.optString("permission"))){
                        isAll = false
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        isAll = false
                        break
                    }
                }
            }
        }
        return isAll
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_PERMISSION_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_PERMISSION_END,"")
    }
}